
(function(){})();
function EQGadget(){
  var baseUrl = "http://china-dizhen.googlecode.com/svn/trunk/";
//  var baseUrl = "";
  this.waitingImg = new Image();
  this.waitingImg.src = baseUrl+"icons/spinner.gif";
  this.map = new EQMap(elem("mapDiv"));
  this.initialTabs(baseUrl);
}
window.EQGadget = EQGadget;
var TabItems = {};

EQGadget.prototype.initialTabs = function(baseUrl){
  TabItems[":hospital"] = new EQTab(this, "hospital", 12, baseUrl+"data/dizhen-yiyuan.v01.json", "http://china-dizhen.googlecode.com/svn/trunk/icons/hospital_32_32.gif");
  TabItems[":bloodDonation"] = new EQTab(this, "bloodDonation", 0, baseUrl+"data/dizhen-xianxue.json", "http://china-dizhen.googlecode.com/svn/trunk/icons/blooddonation_32_32.gif");
  TabItems[":crossRed"] = new EQTab(this, "crossRed", 0, baseUrl+"data/dizhen-redcross.json", "http://china-dizhen.googlecode.com/svn/trunk/icons/redcross_32_32.gif");
  TabItems[":mymaps"] = new EQTab(this, "mymaps", 0, baseUrl+"data/dizhen-mymaps.json", null);
  TabItems[":otherLink"] = new EQTab(this, "otherLink", 0, null, null);
  TabItems[":hospital"].activate();
}
function EQTab(gadget, tabKey, defaultIndex, dataUrl, iconUrl){
  this.gadget = gadget;
  this.map = this.gadget.map;
  this.head = elem(tabKey+"_tab");
  this.container = elem(tabKey+"_cnt");
  this.dataUrl = dataUrl;
  this.iconUrl = iconUrl;
  this.tabKey = tabKey;
  this.defaultIndex = defaultIndex;
  this.initialize();
}
EQTab.prototype.initialize = function(){
  this.deactivate();
  var me = this;
  this.head.onclick = function(){
    me.activate();
  }
}
EQTab.prototype.activate = function(){
  if(this.gadget.curTab == this) return;
  this.head.className = "tab-item active-tab";
  this.container.style.display = "";
  if(this.gadget.curTab){
    this.gadget.curTab.deactivate();
  }
  this.gadget.curTab = this;
  if(this.itemList){
    this.map.reset(this.curItem, this.iconUrl, this.tabKey); 
  } else if(this.dataUrl){
    newEl("div", null, this.container).appendChild(this.gadget.waitingImg);
    var me = this;
    GDownloadUrl(this.dataUrl, function(data){
      var value = eval(data);
      if(me.tabKey == "mymaps"){
        me.initMymaps(value);
      }else{
        me.itemList = value[0];
        me.initSelector();
        me.initQuickSearch();
      }
      me.map.reset(me.curItem, me.iconUrl, me.tabKey);
    });
  } else {
    this.map.reset();
  }
}
EQTab.prototype.deactivate = function(){
  this.head.className = "tab-item";
  this.container.style.display = "none";
}

EQTab.prototype.initSelector = function(){
  this.selector = newEl("select", "select", null);
  for (var itemName in this.itemList) {
    var option = new Option(itemName, itemName);
    this.selector.options[this.selector.options.length] = option;
  }
  this.container.replaceChild(this.selector, this.container.lastChild);
  var me = this;
  var defaultEntityName = this.selector.options[this.defaultIndex].value;
  this.selector.selectedIndex = this.defaultIndex;
  this.curItem = this.itemList[defaultEntityName].detail || this.itemList[defaultEntityName];
  this.changeItem(this.curItem);
  this.selector.onchange = function(){
    var item = me.itemList[this.value].detail || me.itemList[this.value];
    me.changeItem(item);
  }
}
EQTab.prototype.initQuickSearch = function(){
  var wrapper = newEl("div", null, null);
  wrapper.innerHTML = '<input type="text" class="search-input" value = "快速搜索"/><input type="button" class="search-button" value = "搜">';
  this.searchInput = wrapper.firstChild;
  this.searchBtn = wrapper.lastChild;
  this.container.insertBefore(wrapper, this.container.firstChild);
  var me = this;
  this.searchInput.onblur = function(){
    this.style.color = "#999999";
    if(this.value==""){
      this.value = "快速搜索";
    }
  };
  this.searchInput.onfocus = function(){
    this.style.color = "#000";
    if(this.value == "快速搜索"){
      this.value = "";
    }
  };
  this.searchBtn.onclick = function(){
    var value = me.searchInput.value;
    if(value != "" && value != "快速搜索"){
      me.selector.selectedIndex = 0;
      var tempItem = me.searchMatchEntity(value);
      if(tempItem){
        me.changeItem(tempItem);
      } else {
        me.clearListContainer();
        me.listContainer.innerHTML = '<span style="color:#FF0000">没有找到你要的内容</span>';
      }
    }
  };
}
EQTab.prototype.searchMatchEntity = function(value){
  var result = {};
  var flag = false;
  for(var itemName in this.itemList){
    var item = this.itemList[itemName].detail || this.itemList[itemName];
    for(var entityName in item){
      var entity = item[entityName];
      var name = entity.name;
      if(name && name.match(value)){
        flag = true;
        result[name] = entity;
      }
    }
  }
  return flag ? result : null;
}
EQTab.prototype.changeItem = function(item){
  this.clearListContainer();
  this.createEntitiesDom(item);
  this.map.reset(item, this.iconUrl, this.tabKey);
  this.curItem = item;
}
EQTab.prototype.clearListContainer = function(){
  if(this.listContainer){
    this.listContainer.innerHTML = "";
    this.listContainer.scrollTop = 0;
  } else {
    this.listContainer = newEl("div", "list-container", this.container);
  }
}
EQTab.prototype.createEntitiesDom = function(item){
  var me = this;
  for (var entityName in item) {
    var entity = item[entityName];
    var name = entity.name;
    if(name){
      var node = newEl("div", "entity", this.listContainer);
      node.id = "r_"+name;
      newTextEl(name, node);
  
      node.onclick = function(){
        me.entityClick(this.id.substring(2));
      };
      node.onmouseover = function(){
        me.highlight(this);
      };
      node.onmouseout = function(){
        me.unHighlight(this);
      };
    }
  }
}
EQTab.prototype.entityClick = function(name){
  this.map.showMarker(this.curItem[name]);
}
EQTab.prototype.highlight = function(elem) {
  this.unHighlight(this.curEntityElem);
  this.curEntityElem = elem;
  this.curEntityElem.className = "entity highlight";
}

EQTab.prototype.unHighlight = function(elem) {
  if(elem) elem.className = "entity";
  this.curEntityElem = null;
}
EQTab.prototype.initMymaps = function(value) {
  this.itemList = {};
  this.container.innerHTML = "";
  this.container = newEl("div","mymap-container", this.container);
  for (var i = 0, oneMap; oneMap = value[i]; i++) {
    this.createMyMapDom(oneMap);
    this.itemList[oneMap.msid] = oneMap;
  }
}
EQTab.prototype.createMyMapDom = function(oneMap){
  var mapUrl = 'http://ditu.google.com/maps/ms?msa=0&msid=' + oneMap.msid;
  var myUrl = "http://ditu.google.com/ig/add?moduleurl=" +
      "http%3A//ditu.google.com/maps/ms%3Fmsa%3D0%26msid%3D" + oneMap.msid
      + "%26output%3Dghapi&pid=mpl&synd=mpl";
  var title = oneMap.title.length > 50 ? oneMap.title.substr(0, 50) + '...' : oneMap.title;
  var me = this;  
  var wrapper = newEl("div", "mymap-off", this.container);
  var titleNode = newEl("div", "entity", wrapper);
  newTextEl(title, titleNode);
  titleNode.onclick = function(){
    me.myMapClick(oneMap.msid, this.parentNode);
  };
  titleNode.onmouseover = function(){
    me.highlight(this);
  };
  titleNode.onmouseout = function(){
    me.unHighlight(this);
  };      
  newEl("span", "mymap-desc", wrapper).innerHTML = oneMap.desc;
  var bottom = newEl("div", "links", wrapper);
  newLink("", mapUrl, "new", bottom, "查看详细图", null);
  newLink("mymap-save",myUrl, "new", bottom, "保存到我的地图", null);
}
EQTab.prototype.myMapClick = function(msid, node){
  if(this.curNode) this.curNode.className = "mymap-off";
  this.curNode = node;
  this.curNode.className = "mymap-on";
  this.curItem = this.itemList[msid];
  this.map.reset(this.curItem, null, this.tabKey);
}

function EQMap(dom){
  this.defaultLevel = 8;
  this.gmap = new GMap2(dom);
  this.gmap.setCenter(new GLatLng(31.0, 104.2), this.defaultLevel);
  this.satelliteBounds = new GLatLngBounds(new GLatLng(29.81, 102.83), new GLatLng(32.17, 105.28));
  this.init();
  //only for maps version
  this.gmap.addControl(new GLargeMapControl());
  this.gmap.addControl(new GOverviewMapControl());
  this.gmap.enableDoubleClickZoom();
  this.gmap.enableScrollWheelZoom();
}
EQMap.prototype.init = function(){
  var tileUrl = "http://china-earthquake.appspot.com/proxy?x={X}&y={Y}&z={Z}";
  var satelliteCtl = elem("satelliteCheckbox");
  this.needBox = satelliteCtl.lastChild;
  var wrapper = newEl("span","opacity-ctl", satelliteCtl);
  wrapper.innerHTML = '半透明<input type="checkbox" checked>';
  this.opacityBox = wrapper.lastChild;
  var me = this;
  this.needBox.onclick = function(){
    wrapper.style.display = this.checked ? "" : "none";
    me.checkSatelliteTile();
  }
  this.opacityBox.onclick = function(){
    if(!me.satelliteAdded) return;
    var opacity = this.checked ? 0.5 : 1;
    var newTile = new GTileLayerOverlay(new GTileLayer(null, 1, 17, { opacity: opacity, isPng:true, tileUrlTemplate:tileUrl}));
    me.gmap.removeOverlay(me.satelliteTile);
    me.satelliteTile = newTile;
    me.gmap.addOverlay(newTile);
  }
  wrapper.style.display = this.needBox.checked ? "" : "none";
  var curOpacity = this.opacityBox.checked ? 0.5 : 1;
  this.satelliteTile = new GTileLayerOverlay(new GTileLayer(null, 1, 17, {opacity:curOpacity, isPng:true, tileUrlTemplate: tileUrl} ));
  this.satelliteAdded = false;
  this.checkSatelliteTile();
  GEvent.addListener(this.gmap, "zoomend", function(oldL, newL){
    me.checkSatelliteTile();
  });
  GEvent.addListener(this.gmap, "moveend", function(){
    me.checkSatelliteTile();
  });
}
EQMap.prototype.removeOverlays = function(){
  this.gmap.closeInfoWindow();
  for(var m in this.tabOlList){
    var oldOL = this.tabOlList[m];
    this.gmap.removeOverlay(oldOL);
  }
  this.tabOlList = {};
}
EQMap.prototype.reset = function(item, iconUrl, tabKey){
  this.tabKey = tabKey;
  this.removeOverlays();
  if(tabKey == "mymaps"){
    this.addMyMapItem(item);
  } else if(item){
    this.addSelectorItem(item, iconUrl);
  } else{
    this.gmap.setCenter(new GLatLng(31.0, 104.2), this.defaultLevel);
  }
  this.checkSatelliteTile();
}
EQMap.prototype.addMyMapItem = function(item){
  if(item){
    var me = this;
    var url = 'http://ditu.google.com/maps/ms?msa=0&msid=' + item.msid + '&output=kml';
    this.tabOlList[item.msid] = new GGeoXml(url, function(){
      var bounds = me.tabOlList[item.msid].getDefaultBounds();
      var level = me.gmap.getBoundsZoomLevel(bounds);
      var center = bounds.getCenter();
      me.gmap.setCenter(center, level);
    });
    this.gmap.addOverlay(this.tabOlList[item.msid]);
  }else{
    var center = new GLatLng(31.386468,103.875732);
    this.gmap.setCenter(center, 10);
  }
}
EQMap.prototype.addSelectorItem = function(item, iconUrl){
  var geoInfo = item['geoInfo'];
  if (geoInfo) {
    var point = new GLatLng(geoInfo[1], geoInfo[0]);
    this.gmap.setCenter(point, geoInfo[2]);
    for (var entityName in item) {
      var entity = item[entityName];
      if(entity.ll){
        var latlng = new GLatLng(entity.ll.lat, entity.ll.lng);
        this.addMarker(latlng, entity, iconUrl);
      }
    }
  } else {
    var latlngBound = new GLatLngBounds();
    for (var entityName in item) {
      var entity = item[entityName];
      if(entity.ll){
        var latlng = new GLatLng(entity.ll.lat, entity.ll.lng);
        this.addMarker(latlng, entity, iconUrl);
        latlngBound.extend(latlng);
      }
    }

    var center = latlngBound.getCenter();
    item['geoInfo'] = [];
    item['geoInfo'][0] = center.lng();
    item['geoInfo'][1] = center.lat();
    var me = this;
    var level = this.gmap.getBoundsZoomLevel(latlngBound);
    if(level > this.defaultLevel){
      level = this.defaultLevel;
    }
    item['geoInfo'][2] = level;
    this.gmap.setCenter(center, level);
  }
}
EQMap.prototype.checkSatelliteTile = function(){
  var flag = this.needBox.checked;
  if( flag){
    var curBounds = this.gmap.getBounds();
    if(this.satelliteBounds.intersects(curBounds) || this.satelliteBounds.containsBounds(bounds)){
      if(!this.satelliteAdded) this.gmap.addOverlay(this.satelliteTile);
      this.satelliteAdded = true;
    } 
  } else {
    if(this.satelliteAdded) this.gmap.removeOverlay(this.satelliteTile);
    this.satelliteAdded = false;
  }
}
EQMap.prototype.addMarker = function(point, entity, iconUrl){
  var marker;
  if(iconUrl){
    var icon = this.createIcon(iconUrl, new GSize(24,24), new GPoint(12,12), new GPoint(5,12));
	  marker = new GMarker(point, {icon:icon, title:entity.name});
  }else{
    marker = new GMarker(point, {title:entity.name});
  }
  this.tabOlList[entity.name] = marker;
  this.gmap.addOverlay(marker);
  var me = this;
  GEvent.addListener(marker, "click", function() {
    me.gmap.closeInfoWindow();
    me.curMarker = marker;
    var html = me.getInfoWindowHtml(entity);
    marker.openInfoWindowHtml(html, { maxWidth : 320 });
  });
}
EQMap.prototype.showMarker = function(entity){
  this.gmap.closeInfoWindow();
  var html = this.getInfoWindowHtml(entity);
  this.tabOlList[entity.name].openInfoWindowHtml(html, { maxWidth : 320 });
}
EQMap.prototype.getInfoWindowHtml = function(entity){
  var html = '';
  html += '<div style="font-size:1.1em; font-weight:bolder;margin:3px;">'+entity.name+'</div>';
  if(entity.adr) html += '<div style="margin:2px;"><span style="font-weight:bolder;">地址:</span>'+entity.adr+'</div>';
  if(entity.tel) html += '<div style="margin:2px;"><span style="font-weight:bolder;">电话:</span>'+entity.tel+'</div>';
  if(entity.url) html += '<div style="margin:2px;"><span style="font-weight:bolder;">网址:</span><a target="_blank" href="'+entity.url+'">'+entity.url+'</a></div>';
  if(entity.desc) html += '<div style="margin:2px;"><span style="font-weight:bolder;">简介:</span>'+entity.desc+'</div>';
  if(this.tabKey == "hospital"){
    html = html + '<div style="margin:2px;"><span style="font-weight:bolder;">更多：</span><a href="http://www.google.cn/intl/zh-CN/qinren/cse.html" target="_blank">' + '寻找亲人' +
                  '</a></div>';
  }
  return html;
}
EQMap.prototype.createIcon = function(image, size, iconAnchor, bubbleAnchor){
  var icon = new GIcon();
  icon.image = image;
  icon.iconSize = size;
  icon.iconAnchor = iconAnchor;
  icon.infoWindowAnchor = bubbleAnchor;
  return icon;
}
function elem(id){
  return document.getElementById(id);
}
function newEl(tag, className, prt){
  var el = document.createElement(tag);
  if (className) {
    el.className = className;
  }
  if (prt) {
    prt.appendChild(el);
  }
  return el;
}
function newTextEl(text, prt) {
  var el = document.createTextNode(text);
  if (prt) {
    prt.appendChild(el);
  }
  return el;
}
function newLink(className, url, target, prt, lable, handler){
  var link = newEl("a", className, prt);
  link.href = url || "#";
  if(target) link.target = target;
  newTextEl(lable, link);
  if(handler) link.onclick = handler;
  return link;
}